package com.tr.DeadLock;


/**
 * @author TRasdzz
 * @version version-1.0
 * @since 2021/3/11 15:30
 */

//死锁：多个线程互相抱着对方需要的资源，然后形成僵持
public class DeadLock {
    public static void main(String[] args) {
        Makeup g1 = new Makeup(0, "灰姑娘");
        Makeup g2 = new Makeup(1, "白雪公主");

        g1.start();
        g2.start();
    }
}

class Lipsticks {

}

class Mirror {

}

class Makeup extends Thread {
    static final Lipsticks lipsticks = new Lipsticks();
    static final Mirror    mirror    = new Mirror();

    int    choice;//选择
    String girlName;//化妆的人

    Makeup(int choice, String girlName) {
        this.choice = choice;
        this.girlName = girlName;
    }

    @Override
    public void run() {
        try {
            makeup();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //化妆
    private void makeup() throws InterruptedException {
        if (choice == 0) {
            synchronized (lipsticks) {//获得口红的锁
                System.out.println(this.girlName + "获得口红的锁");
                Thread.sleep(1000);
            }
            synchronized (mirror) {
                System.out.println(this.girlName + "获得镜子的锁");
            }
        } else {
            synchronized (mirror) {//获得口红的锁
                System.out.println(this.girlName + "获得镜子的锁");
                Thread.sleep(1000);
            }
            synchronized (lipsticks) {
                System.out.println(this.girlName + "获得口红的锁");
            }
        }
    }
}

